package com.siyoumi.app.modules.sh.service;

import com.alibaba.fastjson.JSONObject;
import com.siyoumi.component.XApp;
import com.siyoumi.component.XRedis;
import com.siyoumi.config.SysConfig;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.util.*;
import com.siyoumi.validator.XValidator;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class QinglongApi {
    public static QinglongApi getInstance() {
        return new QinglongApi();
    }

    protected String getApiUrl(String urlFix) {
        String root = "http://192.168.0.91:5700/";
        if (SysConfig.getIns().isDev()) {
            root = "http://app.sh.siyoumi.com:5700/";
        }

        return XStr.concat(root, urlFix);
    }

    public XReturn setEvn(Integer id, String name, String val) {
        String apiUrl = getApiUrl("open/envs");
        Map<String, Object> data = new HashMap<>();
        data.put("id", id);
        data.put("name", name);
        data.put("value", val);

        XReturn r = api(apiUrl, XHttpClient.METHOD_PUT, data);
        return r;
    }

    public XReturn evnEnable(Integer id) {
        String apiUrl = getApiUrl("open/envs/enable");

        XReturn r = api(apiUrl, XHttpClient.METHOD_PUT, List.of(id));
        return r;
    }

    /**
     * 检查token是否过期
     *
     * @param token
     */
    public boolean checkExpireToken(String token) {
        String apiUrl = getApiUrl("open/envs");
        Map<String, String> data = new HashMap<>();
        data.put("searchValue", "");
        String query = XStr.queryFromMap(data, null, false);

        String url = apiUrl + "?" + query;

        Map<String, String> mapHeader = new HashMap<>();
        mapHeader.put("Authorization", "Bearer " + token);

        XHttpClient client = XHttpClient.getInstance();
        String returnStr = client.get(url, mapHeader);
        XReturn r = parseR(returnStr);
        if (r.getErrCode() == 401) {
            return true;
        }

        return false;
    }

    protected String getToken() {
        String key = "QinglongApi|token";
        String token = XRedis.getBean().get(key);

        if (XStr.hasAnyText(token)) {
            //检查token，是否过期
            boolean expireToken = checkExpireToken(token);
            if (!expireToken) {
                return token;
            }
        }

        String apiUrl = getApiUrl("open/auth/token");
        Map<String, String> postData = new HashMap<>();
        postData.put("client_id", "PItGy67_dim_");
        postData.put("client_secret", "qQH5eRMFC72NJ5av_NKR2pNz");
        String query = XStr.queryFromMap(postData, null, false);

        XReturn r = api(apiUrl + "?" + query);
        if (r.err()) {
            XValidator.err(r);
        }

        JSONObject mapData = (JSONObject) r.getData("data");
        token = mapData.getString("token");
        XRedis.getBean().setEx(key, token, XDate.now().plusDays(2));

        return token;
    }

    protected XReturn api(String url) {
        return api(url, XHttpClient.METHOD_GET, null);
    }

    /**
     * 接口调用
     */
    protected XReturn api(String url, String method, Object data) {
        log.debug(url);
        log.debug(method);
        log.debug(XJson.toJSONString(data));

        Map<String, String> mapHeader = new HashMap<>();
        if (!XStr.contains(url, "open/auth/token")) {
            //非登陆接口，自动添加token
            mapHeader.put("Authorization", "Bearer " + getToken());
        }

        XReturn r = EnumSys.API_ERROR.getR();
        try {
            XHttpClient client = XHttpClient.getInstance();
            String returnStr;
            if (XHttpClient.METHOD_PUT.equals(method)) {
                //put请求
                returnStr = client.putJson(url, mapHeader, data);
            } else if (XHttpClient.METHOD_GET.equals(method)) {
                //get请求
                returnStr = client.get(url, mapHeader);
            } else {
                //post请求
                returnStr = client.postJson(url, mapHeader, data);
            }

            r = parseR(returnStr);
        } catch (Exception ex) {
            r.setErrMsg(ex.getMessage());
        }
        log.debug(XJson.toJSONString(r));

        return r;
    }

    protected XReturn parseR(String returnStr) {
        XReturn r = XReturn.parse(returnStr);
        Integer code = r.getData("code");
        String message = r.getData("message");
        r.setErrCode(code);
        r.setErrMsg(message);
        if (code == 200) {
            r.setErrCode(0);
        }

        return r;
    }
}
